package com.bocai.kelala.ui.travel.stroke.act;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.OnDismissListener;
import com.bocai.kelala.App;
import com.bocai.kelala.R;
import com.bocai.kelala.base.BaseActivity;
import com.bocai.kelala.bean.MessageEvent;
import com.bocai.kelala.bean.MyGradOrderBean;
import com.bocai.kelala.bean.MyPublishStrokeBean;
import com.bocai.kelala.bean.OrderDetailBean;
import com.bocai.kelala.pay.alipay.AlipayApi;
import com.bocai.kelala.pay.simcpux.WxPayApi;
import com.bocai.kelala.ui.travel.main.act.MainActivity;
import com.bocai.kelala.ui.travel.stroke.contract.MyStrokeContract;
import com.bocai.kelala.ui.travel.stroke.module.MyStrokeModule;
import com.bocai.kelala.ui.travel.stroke.presenter.MyStrokePresenter;
import com.bocai.kelala.widget.PayPopupWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by yuanfei on 2017/6/13.
 */

public class MyReserveStrokeDetailActivity extends BaseActivity implements MyStrokeContract.view, View.OnClickListener {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @Inject
    MyStrokePresenter presenter;
    @BindView(R.id.right_btn)
    Button rightBtn;
    @BindView(R.id.ll_delete)
    LinearLayout llDelete;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_car_name1)
    TextView tvCarName1;
    @BindView(R.id.btn_select)
    TextView btnSelect;
    @BindView(R.id.tv_car_phone)
    TextView tvCarPhone;
    @BindView(R.id.tv_order_title)
    TextView tvOrderTitle;
    @BindView(R.id.tv_start_address)
    TextView tvStartAddress;
    @BindView(R.id.tv_end_address)
    TextView tvEndAddress;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_outset_date)
    TextView tvOutsetDate;
    @BindView(R.id.tv_car_age)
    TextView tvCarAge;
    @BindView(R.id.tv_car_name2)
    TextView tvCarName2;
    @BindView(R.id.tv_car_phone2)
    TextView tvCarPhone2;
    @BindView(R.id.tv_server_phone)
    TextView tvServerPhone;
    @BindView(R.id.ll_server)
    LinearLayout llServer;
    @BindView(R.id.btn)
    Button btn;
    String orderId;
    @BindView(R.id.tv_complete_data)
    TextView tvCompleteData;
    @BindView(R.id.ll_complete)
    LinearLayout llComplete;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.ll_back)
    LinearLayout llBack;
    @BindView(R.id.ll_select_data)
    LinearLayout llSelectData;
    private int index = 0;
    PayPopupWindow payPopupWindow;
    private String phone;
    private int flag = 0;
    TimePickerView pickerView;
    OrderDetailBean bean;

    @Override
    public int getLayoutId() {
        return R.layout.act_my_reserve_stroke_detail;
    }

    @Override
    public void initPresenter() {
        App.get(this).getAppComponent().addSub(new MyStrokeModule(this)).inject(this);
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        initToolbar("我的行程");
        initBack(imgBack,llBack);
        orderId = getIntent().getStringExtra("orderId");
        flag = getIntent().getIntExtra("flag",0);
        presenter.orderDetail(orderId);
        btn.setOnClickListener(this);
        llSelectData.setOnClickListener(this);

    }

    @Override
    public void myStrokePublish(MyPublishStrokeBean bean) {

    }

    @Override
    public void myGradOrder(MyGradOrderBean bean) {

    }

    @Override
    public void getOrderDetail(OrderDetailBean bean) {
        this.bean = bean;
//        if (bean.getApplySeats()!=0&& !TextUtils.isEmpty(bean.getArriveCity())) {

        tvOrderTitle.setText("请及时联系司机，告知具体接送信息");
//        }
        flag = 0;
        if (bean.getOrderStatus() == 1) {

            btnSelect.setText("待付款");
            llComplete.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            btn.setText("付款");
            llServer.setVisibility(View.VISIBLE);
            tvServerPhone.setText("价格为"+bean.getPrice()+"元");
            tvServerPhone.setTextColor(getResources().getColor(R.color.color_F18A34));
            ll1.setVisibility(View.VISIBLE);
            index = 1;
            if (payPopupWindow==null) {
                payPopupWindow = new PayPopupWindow(this, bean.getPrice() + "", this);
                payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1f);
                    }
                });
            }
        } else if (bean.getOrderStatus() == 2) {

            btnSelect.setText("待出发");
            llComplete.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            btn.setText("联系司机");
            ll1.setVisibility(View.VISIBLE);
            tvServerPhone.setText("接单后无法取消，请联系客服 0571-57163672");
            tvServerPhone.setTextColor(getResources().getColor(R.color.text_color));
            index = 2;
        } else if (bean.getOrderStatus() == 5) {
            tvOrderTitle.setText(bean.getApplySeats() + "座大客车准点抵达目的地" + bean.getArriveCity());
            btnSelect.setText("行程中");
            llComplete.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            btn.setText("联系司机");
            ll1.setVisibility(View.VISIBLE);
            tvServerPhone.setText("接单后无法取消，请联系客服 0571-57163672");
            tvServerPhone.setTextColor(getResources().getColor(R.color.text_color));
            index = 2;
        }else if (bean.getOrderStatus() == 3) {

            tvNum.setText(bean.getApplySeats()+"人");
            btnSelect.setText("已完成");
            llComplete.setVisibility(View.VISIBLE);
            tvCompleteData.setText("订单已于" + bean.getFinishTime() + " 结束");
            llServer.setVisibility(View.GONE);
            btn.setText("查看车辆证件");
            btn.setVisibility(View.GONE);
            ll1.setVisibility(View.GONE);
            index = 2;
        }else if (bean.getOrderStatus() == 6) {
            btnSelect.setText("待确认");
            llComplete.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            btn.setText("付款");
            btn.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            tvServerPhone.setText("价格为"+bean.getPrice()+"元");
            tvServerPhone.setTextColor(getResources().getColor(R.color.color_F18A34));
            ll1.setVisibility(View.VISIBLE);
            index = 2;
            if (payPopupWindow==null) {
                payPopupWindow = new PayPopupWindow(this, bean.getPrice() + "", this);
                payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1f);
                    }
                });
            }
        }else if (bean.getOrderStatus() == 7) {
            flag = 1;
            btnSelect.setText("已确认");
            llComplete.setVisibility(View.GONE);
            llServer.setVisibility(View.VISIBLE);
            btn.setText("付款");
            llServer.setVisibility(View.VISIBLE);
            tvServerPhone.setText("价格为"+bean.getPrice()+"元");
            tvServerPhone.setTextColor(getResources().getColor(R.color.color_F18A34));
            ll1.setVisibility(View.VISIBLE);
            index = 1;
            if (payPopupWindow==null) {
                payPopupWindow = new PayPopupWindow(this, bean.getPrice() + "", this);
                payPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        backgroundAlpha(1f);
                    }
                });
            }
        }



        phone = bean.getDriverPhone();
        tvNum.setText(bean.getApplySeats()+"人");
        tvCarName1.setText(bean.getOrderMemberName());
        tvCarName2.setText(bean.getDriver());
        tvCarPhone.setText("联系电话 " + bean.getOrderMemberPhone());
        tvCarPhone2.setText(bean.getDriverPhone());
        tvCarAge.setText(bean.getCarAge() + "年");
        tvEndAddress.setText(bean.getArriveCity());
        tvStartAddress.setText(bean.getOriginCity());
        tvOutsetDate.setText(bean.getAppointTime());
        if (flag == 1){
            try {
                setDataView();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (bean.getOrderStatus() == 1||bean.getOrderStatus() == 7||bean.getOrderStatus() == 6) {

            if (!TextUtils.isEmpty(bean.getOrderMemberPhone())) {
                String bb = bean.getOrderMemberPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
                tvCarPhone.setText("联系电话 " +bb);
            }

            if (!TextUtils.isEmpty(bean.getDriverPhone())) {
                String bb = bean.getDriverPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1********");
                tvCarPhone2.setText(bb);
            }

            if (!TextUtils.isEmpty(bean.getOrderMemberName())) {
                String aa = bean.getOrderMemberName().substring(0, 1);
                tvCarName1.setText(aa + "**");
            }

            if (!TextUtils.isEmpty(bean.getDriver())) {
                String aa = bean.getDriver().substring(0, 1);
                tvCarName2.setText(aa + "**");
            }
        }
    }

    @Override
    public void orderPaySuccess(String result) {
//        showShortToast("付款成功");
//        payPopupWindow.dismiss();
//        presenter.orderDetail(orderId);
        payPopupWindow.dismiss();
        if (payPopupWindow.getPayType() == 0) {
            AlipayApi alipayApi = new AlipayApi(this);
            alipayApi.payV2(result);
        }else {
            WxPayApi wxPayApi = new WxPayApi(this);
            wxPayApi.pay(result);
        }

    }

    @Override
    public void cancelOrderSuccess() {


    }

    @Override
    public void addDepartTimeSuccess() {
        presenter.orderDetail(orderId);
        backgroundAlpha(0.5f);
        payPopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void showLoading(String title) {
        startProgressDialog(title);
    }

    @Override
    public void stopLoading() {
        stopProgressDialog();
    }

    @Override
    public void showErrorTip(String msg) {

        if (msg.equals("用户授权失败")){
            msg = "您的登录已失效，请重新登录";
            startActivity(new Intent(this,MainActivity.class).putExtra("index",1));
            finish();
        }
        showShortToast(msg);
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if ("11".equals(event.msg)){
            flag = 0;
            presenter.orderDetail(orderId);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn:
                if (index == 1) {
                    if (flag == 1){
                        if (TextUtils.isEmpty(tvOutsetDate.getText().toString())){
                            showErrorTip("请选择出发时间");
                        }else {
                            presenter.addDepartTime(orderId,tvOutsetDate.getText().toString());
                        }
                    }else{
                        backgroundAlpha(0.5f);
                        payPopupWindow.showAtLocation(findViewById(R.id.main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }

                } else if (index == 2) {
                    checkReadPermission();
                }
                break;
            case R.id.btn_confirm_pay:
                    if (payPopupWindow.getPayType() == 0) {
                        presenter.orderPay("alipayagency",orderId);
                    }else {
                        presenter.orderPay("weixinagency",orderId);
                    }

//                AlipayApi alipayApi = new AlipayApi(this);
//                alipayApi.payV2();
                break;
            case R.id.ll_select_data:
                if (flag == 1) {
                    pickerView.show();
                }
                break;
        }
    }

    public void setCallPhone(){
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:"+phone));
        startActivity(intent);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkReadPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            //应用还未获取读取拨打电话 的权限，询问是否允许
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 222);
        } else {
            setCallPhone();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 222){
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                setCallPhone();
            } else {
                showErrorTip("权限被禁止，请在设置中打开权限");
            }
        }
    }
    public void setDataView() throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        // 指定一个日期
        final Date date1 = dateFormat.parse(bean.getBeginTime());

        final Date date2 = dateFormat.parse(bean.getEndTime());
        // 对 calendar 设置为 date 所定的日期

        Calendar calendar1 = Calendar.getInstance();
        Calendar calendar2 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar2.setTime(date2);
        pickerView = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                if (date.before(date1)){
                    showErrorTip("选择时间早于开始时间");
                }else if (date.after(date2)){
                    showErrorTip("选择时间晚于结束时间");
                }else {
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String str=sdf.format(date);
                    tvOutsetDate.setText(str);
                }

            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                .setRangDate(calendar1, calendar2)
                .build();
        pickerView.setDate(calendar1);//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
//        pickerView.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
